package com.yky.action.index;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import com.yky.action.base.BaseActionSupport;
import com.yky.entity.Organization;
import com.yky.entity.Project;
import com.yky.entity.ProjectEthic;
import com.yky.entity.ProjectGroup;
import com.yky.entity.ProjectIndicator;
import com.yky.entity.ProjectOrganization;
import com.yky.entity.Province;
import com.yky.entity.User;
import com.yky.model.OrgEntity;
import com.yky.model.ProvinceEntity;
import com.yky.service.admin.OrganizationService;
import com.yky.service.admin.ProjectEthicService;
import com.yky.service.admin.ProjectGroupService;
import com.yky.service.admin.ProjectIndicatorService;
import com.yky.service.admin.ProjectOrganizationService;
import com.yky.service.admin.ProjectReportService;
import com.yky.service.admin.ProjectService;
import com.yky.service.admin.ProjectSummarizeService;
import com.yky.service.admin.ProvinceService;
import com.yky.utils.JsonUtil;

/**
 * 项目检索
 * 
 * @author vimesly
 * 
 */

@ParentPackage("perInterceptor")
@InterceptorRefs({@InterceptorRef("sessionStack")})
@Namespace(value = "/index")
public class ProjectSearchAction extends BaseActionSupport {

	private static final long serialVersionUID = 1L;

	private Integer id;
	private String searchText;
	private String provinceCode;
	private String orgId;

	private String pageIndex;
	private String pageShowCount;

	@Autowired
	private ProvinceService provinceService;
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectEthicService projectEthicService;
	@Autowired
	private ProjectGroupService projectGroupService;
	@Autowired
	private ProjectIndicatorService projectIndicatorService;
	@Autowired
	private ProjectReportService projectReportService;
	@Autowired
	private ProjectSummarizeService projectSummarizeService;
	@Autowired
	private ProjectOrganizationService projectOrganizationService;

	public String find() {
		HttpServletRequest request = ServletActionContext.getRequest();
		User user = (User) request.getSession(false).getAttribute("user");
		HashMap<String, Object> r = new LinkedHashMap<String, Object>();
		try {
			Project project = projectService.find(id);
			if (user == null && !"1".equals(project.getStatus())) {
				// 公众用户只能看审核已通过的信息
				return null;
			}
			r.put("project", project);
			// 项目组织信息
			List<ProjectOrganization> poList = projectOrganizationService
					.findByPropertys("o.project=?", new Object[] { project });
			if (poList.size() > 0) {
				r.put("projectOrganization", poList.get(0));
			}
			// 伦理审查信息
			List<ProjectEthic> peList = projectEthicService.findByPropertys(
					"o.project=?", new Object[] { project });
			if (peList.size() > 0) {
				r.put("projectEthic", peList.get(0));
				Province province = provinceService.find(peList.get(0)
						.getProvinceCode());
				if(province!=null) {
					r.put("projectEthicProvinceName", province.getName());
				}
			}
			// 组信息
			List<ProjectGroup> pgList = projectGroupService.findByPropertys(
					"o.project=?", new Object[] { project });
			r.put("projectGroupList", pgList);
			// 主要结局信息
			List<ProjectIndicator> piListMain = projectIndicatorService
					.findByPropertys("o.project=? and o.type=?", new Object[] {
							project, "0" });
			if (piListMain.size() > 0) {
				r.put("projectIndicatorMain", piListMain.get(0));
			}
			// 次要结局信息
			List<ProjectIndicator> piListMinor = projectIndicatorService
					.findByPropertys("o.project=? and o.type=?", new Object[] {
							project, "1" });
			r.put("projectIndicatorListMinor", piListMinor);
			// 其他结局信息
			List<ProjectIndicator> piListElse = projectIndicatorService
					.findByPropertys("o.project=? and o.type=?", new Object[] {
							project, "2" });
			r.put("projectIndicatorListElse", piListElse);
			super.printWriterJsonToPage(JsonUtil.formatToJson(r));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	// 获得该省份下的机构
	public String getOrgListByProvince() throws Exception {
		List<OrgEntity> orgEntityList = new ArrayList<OrgEntity>();
		OrgEntity aOrgEntity = null;
		Province aProvince = provinceService.find(provinceCode);
		HttpServletRequest request = ServletActionContext.getRequest();
		User user = (User) request.getSession(false).getAttribute("user");
		if (user == null || user.getRoleType() == 0 || user.getRoleType() == 1) {
			// 大众用户||卫计委管理员（查询所有）|| 省级管理员
			List<Organization> orgList = organizationService.findByPropertys(
					"o.province=? and o.status=?", new Object[] { aProvince, 1});
			for (int j = 0; j < orgList.size(); j++) {
				Organization aOrganization = orgList.get(j);
				aOrgEntity = new OrgEntity();
				aOrgEntity.setOrgName(aOrganization.getName());
				aOrgEntity.setOrgId(aOrganization.getId() + "");
				String pinSQL="";
				if(user != null){
					if(user.getRoleType() !=1 ){
						pinSQL="and o.isTwoCommittees='1'";
					}
				}else{
					pinSQL="and o.isTwoCommittees='1'";
				}
				
				List<Project> poList = projectService.findByPropertys(
						"o.organization=? and ( (o.status='1' and o.isProvinceManagerAudit is null "+pinSQL+" ) or (o.status='1' and o.isProvinceManagerAudit='1' "+pinSQL+") ) ", new Object[] {
								aOrganization});
				aOrgEntity.setCount(poList.size());
				orgEntityList.add(aOrgEntity);
			}
		} else if (user.getRoleType() == 2 || user.getRoleType() == 3) {
			// 机构管理员||机构用户
			aOrgEntity = new OrgEntity();
			aOrgEntity.setOrgName(user.getOrganization().getName());
			aOrgEntity.setOrgId(user.getOrganization().getId() + "");
			List<Project> poList = projectService.findByPropertys(
					"o.organization=? and ( (o.status='1' and o.isProvinceManagerAudit is null ) or (o.status='1' and o.isProvinceManagerAudit='1' ) ) ", new Object[] {
							user.getOrganization()});
			aOrgEntity.setCount(poList.size());
			orgEntityList.add(aOrgEntity);
		}
		super.printWriterJsonToPage(JsonUtil.formatToJson(orgEntityList));
		return null;
	}

	// 查询省份和机构列表
	public String getProvinceList() {
		try {
			List<ProvinceEntity> r = new ArrayList<ProvinceEntity>();
			ProvinceEntity aProvinceEntity = null;

			HttpServletRequest request = ServletActionContext.getRequest();
			User user = (User) request.getSession(false).getAttribute("user");
			if (user == null || user.getRoleType() == 0) {
				// 大众用户||卫计委管理员（查询所有）
				List<Province> list = provinceService.findEntityList();
				for (int i = 0; i < list.size(); i++) {
					Province aProvince = list.get(i);
					List<Project> pList = projectService.findByPropertys(
							"o.organization.province=? and ( (o.status='1' and o.isProvinceManagerAudit is null and o.isTwoCommittees='1') or (o.status='1' and o.isProvinceManagerAudit='1' and o.isTwoCommittees='1') ) ",
							new Object[] { aProvince});
					aProvinceEntity = new ProvinceEntity();
					aProvinceEntity.setProvinceName(aProvince.getName());
					aProvinceEntity.setProvinceCode(aProvince.getCode());
					
					/*List<Project> projectList =new ArrayList<Project>();
					String[] str={"CMR-20161214-1001","CMR-20161129-1003","CMR-20161214-1002","CMR-20161214-1004","CMR-20161213-1001","CMR-20161213-1003"};
					for (int k = 0; k < pList.size(); k++) {
						Project project =pList.get(k);
						for (int j = 0; j < str.length; j++) {
							if(project.getRegNumber().equals(str[j])){
								projectList.add(project);
							}
						}
					}*/
					aProvinceEntity.setCount(pList.size());
					r.add(aProvinceEntity);
				}
			} else if (user.getRoleType() == 1 || user.getRoleType() == 2
					|| user.getRoleType() == 3) {
				// 省级管理员 || 机构管理员||机构用户
				aProvinceEntity = new ProvinceEntity();
				aProvinceEntity.setProvinceCode(user.getProvince().getCode());
				aProvinceEntity.setProvinceName(user.getProvince().getName());
				List<Project> pList = projectService.findByPropertys(
						"o.organization.province=? and ( (o.status='1' and o.isProvinceManagerAudit is null and o.isTwoCommittees='1') or (o.status='1' and o.isProvinceManagerAudit='1' and o.isTwoCommittees='1') ) ",
						new Object[] { user.getProvince() });
				aProvinceEntity.setCount(pList.size());
				r.add(aProvinceEntity);
			}
			super.printWriterJsonToPage(JsonUtil.formatToJson(r));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	public String getPageCount() throws Exception {
		// TODO Auto-generated method stub
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			User user = (User) request.getSession(false).getAttribute("user");

			String searchHql_pro = ""; // 省份查询hql
			String searchHql_org = ""; // 机构查询hql
			String pinSQL="";
			if (searchText == null || "项目名称".equals(searchText)) {
				searchText = "";
			}

			if (user == null || user.getRoleType() == 0) {
				// 大众用户||卫计委管理员（查询所有）
				if (provinceCode != null && !"".equals(provinceCode)) {
					searchHql_pro = " and o.organization.province.code="
							+ provinceCode + " ";
				}
				if (orgId != null && !"".equals(orgId)) {
					searchHql_org = " and o.organization.id=" + orgId + " ";
				}
				pinSQL="and o.isTwoCommittees='1'";
			} else if (user.getRoleType() == 1) {
				// 省级管理员
				searchHql_pro = " and o.organization.province.code="
						+ user.getProvince().getCode() + " ";
				if (orgId != null && !"".equals(orgId)) {
					searchHql_org = " and o.organization.id=" + orgId + " ";
				}
			} else if (user.getRoleType() == 2 || user.getRoleType() == 3) {
				// 机构管理员||机构用户
				searchHql_pro = " and o.organization.province.code="
						+ user.getProvince().getCode() + " ";
				searchHql_org = " and o.organization.id="
						+ user.getOrganization().getId() + " ";
			}

			int count = 0;
			List<Project> list = projectService.findByPropertys(
					"o.name like ? and ( (o.status='1' and o.isProvinceManagerAudit is null "+pinSQL+" ) or (o.status='1' and o.isProvinceManagerAudit='1' "+pinSQL+") ) " + searchHql_pro
							+ searchHql_org, new Object[] { "%" + searchText
							+ "%" });
			/*List<Project> projectList =new ArrayList<Project>();
			String[] str={"CMR-20161214-1001","CMR-20161129-1003","CMR-20161214-1002","CMR-20161214-1004","CMR-20161213-1001","CMR-20161213-1003"};
			for (int i = 0; i < list.size(); i++) {
				Project project =list.get(i);
				for (int j = 0; j < str.length; j++) {
					if(project.getRegNumber().equals(str[j])){
						projectList.add(project);
					}
				}
			}*/
			if (list != null) {
				count = list.size();
			}
			super.pringWriterToPage(JsonUtil.formatToJson(count));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

	public String getPageList() throws Exception {
		// TODO Auto-generated method stub
		HttpServletRequest request = ServletActionContext.getRequest();
		User user = (User) request.getSession(false).getAttribute("user");

		String searchHql_pro = ""; // 省份查询hql
		String searchHql_org = ""; // 机构查询hql
		String pinSQL="";
		
		if (searchText == null || "项目名称".equals(searchText)) {
			searchText = "";
		}

		if (user == null || user.getRoleType() == 0) {
			// 大众用户||卫计委管理员（查询所有）
			if (provinceCode != null && !"".equals(provinceCode)) {
				searchHql_pro = " and o.organization.province.code="
						+ provinceCode + " ";
			}
			if (orgId != null && !"".equals(orgId)) {
				searchHql_org = " and o.organization.id=" + orgId + " ";
			}
			pinSQL="and o.isTwoCommittees='1'";
		} else if (user.getRoleType() == 1) {
			// 省级管理员
			searchHql_pro = " and o.organization.province.code="
					+ user.getProvince().getCode() + " ";
			if (orgId != null && !"".equals(orgId)) {
				searchHql_org = " and o.organization.id=" + orgId + " ";
			}
		} else if (user.getRoleType() == 2 || user.getRoleType() == 3) {
			// 机构管理员||机构用户
			searchHql_pro = " and o.organization.province.code="+ user.getProvince().getCode() + " ";
			searchHql_org = " and o.organization.id="
					+ user.getOrganization().getId() + " ";
		}

		List<Map<Object, Object>> result = new ArrayList<Map<Object, Object>>();
		List<Project> list = null;
		try {

			int page = Integer.valueOf(pageIndex);
			int maxResult = Integer.valueOf(pageShowCount);
			int firstResult = maxResult * page;
			LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
			orderBy.put("regNumber", "desc");
			list = projectService.findByPropertys(page, maxResult
					* (page + 1), " o.name like ? and ( (o.status='1' and o.isProvinceManagerAudit is null "+pinSQL+" ) or (o.status='1' and o.isProvinceManagerAudit='1' "+pinSQL+") ) "
					+ searchHql_pro + searchHql_org, new Object[] { "%"
					+ searchText + "%" }, orderBy);
			
			/*List<Project> projectList =new ArrayList<Project>();
			String[] str={"CMR-20161214-1001","CMR-20161129-1003","CMR-20161214-1002","CMR-20161214-1004","CMR-20161213-1001","CMR-20161213-1003"};
			for (int i = 0; i < list.size(); i++) {
				Project project =list.get(i);
				for (int j = 0; j < str.length; j++) {
					if(project.getRegNumber().equals(str[j])){
						projectList.add(project);
					}
				}
			}*/
			
			if (null != list) {
				Map<Object, Object> map = null;
				for (Project obj : list) {
					map = new HashMap<Object, Object>();
					map.put("id", obj.getId());
					map.put("name", obj.getName());
					map.put("regNumber", obj.getRegNumber());
					map.put("researchType", obj.getResearchType());
					map.put("organizationName", obj.getOrganization().getName());
					map.put("createTime", obj.getCreateTime());
					result.add(map);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String content = JsonUtil.formatToJson(result);
		super.pringWriterToPage(content);
		return null;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getSearchText() {
		return searchText;
	}

	public void setSearchText(String searchText) {
		this.searchText = searchText;
	}

	public String getProvinceCode() {
		return provinceCode;
	}

	public void setProvinceCode(String provinceCode) {
		this.provinceCode = provinceCode;
	}

	public String getOrgId() {
		return orgId;
	}

	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}

	public String getPageIndex() {
		return pageIndex;
	}

	public void setPageIndex(String pageIndex) {
		this.pageIndex = pageIndex;
	}

	public String getPageShowCount() {
		return pageShowCount;
	}

	public void setPageShowCount(String pageShowCount) {
		this.pageShowCount = pageShowCount;
	}

}
